/**
 * 通用存储工具
 * 兼容微信小程序、H5、App等平台
 */

// 获取存储实例
const getStorage = () => {
  // #ifdef MP-WEIXIN
  return uni.getStorageSync ? {
    getItem: (key) => {
      try {
        return uni.getStorageSync(key);
      } catch (e) {
        console.warn('getStorageSync error:', e);
        return null;
      }
    },
    setItem: (key, value) => {
      try {
        uni.setStorageSync(key, value);
        return true;
      } catch (e) {
        console.warn('setStorageSync error:', e);
        return false;
      }
    },
    removeItem: (key) => {
      try {
        uni.removeStorageSync(key);
        return true;
      } catch (e) {
        console.warn('removeStorageSync error:', e);
        return false;
      }
    }
  } : null;
  // #endif
  
  // #ifdef H5
  return typeof localStorage !== 'undefined' ? localStorage : null;
  // #endif
  
  // #ifdef APP-PLUS
  return uni.getStorageSync ? {
    getItem: (key) => {
      try {
        return uni.getStorageSync(key);
      } catch (e) {
        console.warn('getStorageSync error:', e);
        return null;
      }
    },
    setItem: (key, value) => {
      try {
        uni.setStorageSync(key, value);
        return true;
      } catch (e) {
        console.warn('setStorageSync error:', e);
        return false;
      }
    },
    removeItem: (key) => {
      try {
        uni.removeStorageSync(key);
        return true;
      } catch (e) {
        console.warn('removeStorageSync error:', e);
        return false;
      }
    }
  } : null;
  // #endif
  
  return null;
};

const storage = getStorage();

// 安全的存储操作
export const safeStorage = {
  getItem: (key) => {
    if (!storage) {
      console.warn('Storage not available on this platform');
      return null;
    }
    return storage.getItem(key);
  },
  
  setItem: (key, value) => {
    if (!storage) {
      console.warn('Storage not available on this platform');
      return false;
    }
    return storage.setItem(key, value);
  },
  
  removeItem: (key) => {
    if (!storage) {
      console.warn('Storage not available on this platform');
      return false;
    }
    return storage.removeItem(key);
  }
};

export default safeStorage; 